import os

# callback management
import wsgiref.handlers

# class base for controller
from google.appengine.api import users, images
from google.appengine.ext import webapp

# needed for routing and display
import category, wiki, author, collection, exposition, picture
import contact, language, settings, size, yams

# Image tools
from getimageinfo import getImageInfo

class ImgRequest (webapp.RequestHandler):
    """
    """

    def get(self):
        """
        """
        # use clip for a menu for example
        max_size_str = self.request.get("max_size")
        if not max_size_str == '':
            max_size = float(max_size_str)
        else:
            max_size = None

        size_str = self.request.get("size")
        if not size_str == '':
            screen_width = float(size_str)
        else:
            screen_width = 1024

        if max_size and screen_width > max_size:
            screen_width = max_size

        nb_of_pictures_str = self.request.get("nb_of_pictures")
        if not nb_of_pictures_str == '':
            nb_of_pictures = int(nb_of_pictures_str)
        else:
            nb_of_pictures = 1

        img = None
        html_img = None

        url = self.request.get("url")
        if not url == '':
            #
            try:
                # compute the path
                root_path = os.path.abspath('.')
                url = url.replace('-', '/')
                path = os.path.join(root_path, 'resources', 'img', url)
                # read the file
                file = open(path, 'rb')
                data = file.read()
                file.close()
                if data:
                    content_type, width, height = getImageInfo(data)
                    html_img = images.Image(data)
                    #
                    img_width = screen_width / (nb_of_pictures + 1)
                    ratio = float(width) / img_width
                    img_height = float(height) / ratio
            except Exception, e:
                self.response.out.write(e)

        if not html_img:
            return

        #
        html_img.resize(width=int(img_width), height=int(img_height))
        #
        html_img.im_feeling_lucky()
        # compute the new image
        thumbnail = html_img.execute_transforms()

        if thumbnail:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(thumbnail)

        else:
            self.error(404)

class Login(webapp.RequestHandler):
    '''
    '''
    def get(self):
        '''
        '''
        self.redirect(users.create_login_url('/'))

class Logout(webapp.RequestHandler):
    '''
    '''
    def get(self):
        '''
        '''
        # get the current user
        user = users.get_current_user()

        # logout the current user
        if user:
            self.redirect(users.create_logout_url('/'))

def main():
    application = webapp.WSGIApplication(
                    [
                    #
                    ('/img', ImgRequest),
                    ('/login', Login),
                    ('/logout', Logout),

                    #
                    ('/', wiki.Index),
                    #
                    ('/wiki', wiki.Index),
                    ('/wiki/edit', wiki.Edit),
                    ('/wiki/save', wiki.Save),
                    ('/wiki/position', wiki.Position),

                    #
                    ('/category/edit', category.Edit),
                    ('/category/save', category.Save),
                    ('/category/position', category.Position),

                    #
                    ('/author/show', author.Index),
                    ('/author/edit', author.Edit),
                    ('/author/save', author.Save),

                    #
                    ('/collection/show', collection.Index),
                    ('/collection/edit', collection.Edit),
                    ('/collection/save', collection.Save),

                    #
                    ('/exposition', exposition.Index),
                    ('/exposition/edit', exposition.Edit),
                    ('/exposition/save', exposition.Save),
                    ('/exposition/update_date', exposition.Update_date),

                    #
                    ('/rss', picture.RSS),
                    ('/picture', picture.Index),
                    ('/picture/new', picture.New),
                    ('/picture/author', picture.Author),
                    ('/picture/collection', picture.Collection),
                    ('/picture/exposition', picture.Exposition),
                    ('/picture/edit', picture.Edit),
                    ('/picture/save', picture.Save),
                    ('/picture/edit_image', picture.EditImage),
                    ('/picture/save_image', picture.SaveImage),

                    #
                    ('/contact', contact.Index),
                    ('/contact/edit', contact.Edit),
                    ('/contact/save', contact.Save),

                    #
                    ('/settings/edit', settings.Edit),
                    ('/settings/save', settings.Save),

                    #
                    ('/language', language.Select),
                    ('/language/edit', language.Edit),
                    ('/language/save', language.Save),

                    #
                    ('/size', size.Select),
                    ('/size/edit', size.Edit),
                    ('/size/save', size.Save),

                    #
                    ('/yams', yams.Index),
                    ('/yams/player', yams.Player),
                    ('/yams/create_game', yams.CreateGame),
                    ('/yams/choose_game', yams.ChooseGame),
                    ('/yams/roll', yams.Roll),
                    ('/yams/score', yams.Score),
                    ('/yams/admin/delete_player', yams.DeletePlayer),
                    ('/yams/admin/delete_game', yams.DeleteGame),
                    ('/yams/show_game', yams.ShowGame),
                    ],
                    debug=True)

    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
